package com.lsu.singleton.homework;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;

/**
 * 连接池
 *
 * @Author wang suo
 * @Date 2020/12/24 0024 8:08
 * @Version 1.0
 */
public class ConnectionPool {
    private int maxConn = 30;
    private int minConn = 20;
    private int nowConn = 0;
    private static LinkedList<Connection> connections = new LinkedList<>();

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void newConnection() {
        try {
            connections.addLast(DriverManager.getConnection("", "", ""));
            nowConn++;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private ConnectionPool() {
        for (int i = 0; i < minConn; i++) {
            newConnection();
        }
        System.out.println("数据库连接池初始化完毕,当前已创建连接个数为:" + nowConn);
    }

    public synchronized Connection getConnection() {
        if (connections.size() > 0) {
            System.out.println("成功获取连接!");
            return connections.removeLast();
        }
        if (nowConn < maxConn) {
            newConnection();
            System.out.println("增加连接,当前已创建的连接数: " + nowConn);
            System.out.println("成功获取连接!");
            return connections.removeLast();
        }
        return null;
    }
}
